package com.googlecode.javaexamples.multithreading.ringbuffer;

public class WriterThread extends Thread {
    private boolean needToStop;
    private int messageCounter = 0;
    private Object lockObject;
    private RingBuffer<String> buffer;

    public WriterThread(RingBuffer<String> buffer, Object lockObject) {
        super();
        this.buffer = buffer;
        this.setDaemon(true);
        this.lockObject = lockObject;
        this.setName("Writer " + this.getName());
    }

    public void run() {
        while (!needToStop) {
            synchronized (lockObject) {
                if (buffer.elementCount() < buffer.size()) {
                    buffer.push("Thread " + Thread.currentThread().getName()
                            + " generate message " + messageCounter);
                    ++messageCounter;
                    lockObject.notifyAll();
                } else {
                    try {
                        lockObject.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void stopWriter() {
        needToStop = true;
    }
}
